import { defineStore } from 'pinia';
import { store } from '@/store';
import { getStorageSync, setStorageSync } from '@tarojs/taro';
import Taro from '@tarojs/taro';

const CART_KEY = 'CART_KEY';

export interface CartItem {
  id: string | number;
  typeName: string;
  price: number;
  pic?: string;
  quantity: number;
  goodsType_dictText?: string;
  selected: boolean;
}

interface CartState {
  items: CartItem[];
}

// Helper function to save cart to storage
function saveCart(items: CartItem[]) {
  setStorageSync(CART_KEY, items);
}

export const useCartStore = defineStore({
  id: 'cart',
  state: (): CartState => ({
    items: (getStorageSync(CART_KEY) || []).map((item: Omit<CartItem, 'selected'>) => ({
      ...item,
      selected: true, // Default to selected when loading
    })),
  }),
  getters: {
    selectedItems(): CartItem[] {
        return this.items.filter(item => item.selected);
    },
    totalItems(): number {
      return this.selectedItems.reduce((total, item) => total + Number(item.quantity), 0);
    },
    totalPrice(): string {
      const total = this.selectedItems.reduce((total, item) => total + item.price * item.quantity, 0);
      return total.toFixed(2);
    },
    areAllSelected(): boolean {
        return this.items.length > 0 && this.items.every(item => item.selected);
    }
  },
  actions: {
    addToCart(product: Omit<CartItem, 'quantity' | 'selected'>, total = 1) {
      const existingItem = this.items.find(item => item.id === product.id);
      if (existingItem) {
        existingItem.quantity += total;
      } else {
        this.items.push({ ...product, quantity: total, selected: true });
      }
      saveCart(this.items);
      Taro.showToast({
        title: '已添加到购物车',
        icon: 'success'
      });
    },
    removeFromCart(productId: string | number) {
      this.items = this.items.filter(item => item.id !== productId);
      saveCart(this.items);
    },
    updateItemQuantity(productId: string | number, quantity: number) {
      const item = this.items.find(item => item.id === productId);
      if (item) {
        if (quantity > 0) {
          item.quantity = quantity;
        } else {
          // remove if quantity is 0 or less
          this.removeFromCart(productId);
        }
      }
      saveCart(this.items);
    },
    clearCart() {
        this.items = [];
        saveCart(this.items);
    },
    toggleItemSelection(productId: string | number) {
        const item = this.items.find(item => item.id === productId);
        if (item) {
            item.selected = !item.selected;
        }
        saveCart(this.items);
    },
    toggleSelectAll(select: boolean) {
        this.items.forEach(item => item.selected = select);
        saveCart(this.items);
    }
  }
});

export function useCartStoreWithOut() {
  return useCartStore(store);
} 